package com.evil.common.file.enums;

import com.evil.common.core.enums.BaseEnum;
import com.evil.common.core.exception.BusinessException;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.Optional;
import java.util.regex.Pattern;

/**
 * 文件类型
 *
 * @author liyang
 */
@Getter
@AllArgsConstructor
public enum FileTypeEnum {
    /**
     * 文件类型
     */
    OTHER(0, "其他", "file", null),
    IMAGE(1, "图片", "image", ".+(jpeg|jpg|gif|png|bmp)$"),
    VIDEO(2, "视频", "video", ".+(mp4|flv|rmvb|3gp|avi|wmv|swf|mov)$"),
    VOICE(3, "语音", "voice", ".+(mp3|m4a|flac|wav)$"),
    FOLDER(99, "文件夹", "folder", null),
    ;

    private final int id;
    private final String title;
    private final String extension;
    private final String pattern;

    public boolean checkPattern(String extension) {
        return null != pattern && Pattern.matches(pattern, extension);
    }

    public static Optional<FileTypeEnum> isExistById(Integer id) {
        if (null == id) {
            return Optional.empty();
        }
        return Arrays.stream(values()).filter(e -> e.id == id).findFirst();
    }

    public static FileTypeEnum findById(Integer id) {
        return FileTypeEnum.isExistById(id).orElseThrow(FileTypeEnum::error);
    }

    public static Optional<FileTypeEnum> isExistByExtension(String extension) {
        if (StringUtils.isBlank(extension)) {
            return Optional.empty();
        }
        extension = extension.toLowerCase();
        extension = extension.startsWith(".") ? extension : "." + extension;
        for (FileTypeEnum e : values()) {
            if (e.checkPattern(extension)) {
                return Optional.of(e);
            }
        }
        return Optional.empty();
    }

    public static FileTypeEnum findByExtension(String extension) {
        return FileTypeEnum.isExistByExtension(extension).orElseThrow(FileTypeEnum::error);
    }

    public static Integer getIdByExtension(String extension) {
        return FileTypeEnum.isExistByExtension(extension).orElse(OTHER).id;
    }

    public static BusinessException error() {
        return new BusinessException(BaseEnum.ERROR_PARAMETER, "文件类型错误");
    }
}
